package com.example.demo.beanproxy;

import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.InterceptorChain;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @Author: zhouhong
 * @Date: Created in 14:18 2018/5/7
 * @ModifiedBy:
 * @Description: 为bean创建代理类,实现插件化
 */
@Component
public class BeanProxyProcessor implements BeanPostProcessor {
    private final InterceptorChain interceptorChain;
    public BeanProxyProcessor(ObjectProvider<Interceptor[]> intrtceptorProvider) {
        Interceptor[] interceptors=intrtceptorProvider.getIfAvailable();
        interceptorChain=new InterceptorChain();//初始化插件链
        if(null!=interceptors && interceptors.length>0){//有插件，加载插件
            for(int i=0;i<interceptors.length;i++){
                interceptorChain.addInterceptor(interceptors[i]);//添加插件
            }
        }
    }

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        Annotation annotation=bean.getClass().getAnnotation(Service.class);
        Class<?> interfaces[]=bean.getClass().getInterfaces();
        if(null!=annotation && interfaces.length>0){//为service层(有接口的service)注解的方法生产代理
            //增加插件
            return interceptorChain.pluginAll(bean);
        }
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }

}
